package com.xhldtc.proxy;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Locale;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;

public class HttpHandler implements HttpRequestHandler
{
	public void handle(final HttpRequest request, final HttpResponse response,
			final HttpContext context) throws HttpException, IOException
	{

		String method = request.getRequestLine().getMethod()
				.toUpperCase(Locale.ENGLISH);
		if (!method.equals("GET") && !method.equals("HEAD")
				&& !method.equals("POST"))
		{
			throw new MethodNotSupportedException(method
					+ " method not supported");
		}
		String target = request.getRequestLine().getUri();

		RequestLine rl = request.getRequestLine();

		System.out.println(rl.getMethod() + " " + rl.getUri() + " "
				+ rl.getProtocolVersion());

		for (Header h : request.getAllHeaders())
		{
			System.out.println(h.getName() + "=" + h.getValue());
		}

		if (request instanceof HttpEntityEnclosingRequest)
		{
			HttpEntity entity = ((HttpEntityEnclosingRequest) request)
					.getEntity();
			byte[] entityContent = EntityUtils.toByteArray(entity);
			System.out.println("Incoming entity content (bytes): "
					+ entityContent.length);
			System.out.println("Entity: " + EntityUtils.toString(entity));
		}

		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet hg = new HttpGet("http://localhost:8080/proxy/main?uri="
				+ URLEncoder.encode(request.getRequestLine().getUri(), "UTF-8"));

		hg.setHeaders(request.getAllHeaders());

		HttpResponse resp = client.execute(hg);

		response.setStatusLine(resp.getStatusLine());
		response.setEntity(resp.getEntity());
		response.setHeaders(resp.getAllHeaders());
		response.setLocale(resp.getLocale());
		response.setParams(resp.getParams());

	}

}
